<template>
  <!-- 目录列表从这里开始 -->
  <div class="container">
    <!-- 卡片视图 -->
    <el-card>
      <!-- 面包屑导航  -->
      <el-breadcrumb v-if="urlInfo" separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/subjects/list' }"
          >学科管理</el-breadcrumb-item
        >
        <el-breadcrumb-item>{{ urlInfo.name }}</el-breadcrumb-item>
        <el-breadcrumb-item>目录管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 水平线区域 -->
      <hr v-if="urlInfo" class="hr" />
      <!-- 搜索区域 -->
      <el-row :class="urlInfo ? 'searchRow' : ''">
        <el-col :span="7" class="strong">
          目录名称<el-input
            v-model="directoryName"
            placeholder="请输入内容"
            @change="searchSwitch = true"
          ></el-input
        ></el-col>
        <el-col :span="9" class="strong"
          >状态
          <!-- 状态选择框 -->
          <el-select
            @change="searchSwitch = true"
            v-model="state"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

          <el-button class="leftBtn" @click="clearBtn">清除</el-button
          ><el-button type="primary" @click="searchBookLise">搜索 </el-button>

        </el-col>
        <el-col :span="5" :push="4">
          <span v-if="urlInfo" @click="$router.go(-1)" class="closeObject"
            ><i class="el-icon-back"></i>返回学科</span
          ><el-button
            :class="urlInfo ? '' : 'addDirectory'"
            size="small"
            type="success"
            @click="addDirectoryDialog = true"
            >新增目录</el-button
          >
          <el-button class="oop">王浩颖</el-button>
        </el-col>
      </el-row>
      <!-- 信息提示 -->
      <el-alert :closable="false" show-icon type="info"
        >数据一共{{ counts }}条</el-alert
      >

      <!-- 表格区域 -->
      <el-table :data="bookList" style="width: 100%;">
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="subjectName" label="所属学科"> </el-table-column>
        <el-table-column prop="directoryName" label="目录名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者"> </el-table-column>
        <el-table-column label="创建日期">
          <template slot-scope="scope">
            {{
              scope.row.addDate | parseTimeByString("{y}-{m}-{d}  {h}:{i}:{s}")
            }}
          </template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.state">已启用</span>
            <span v-else>已禁用</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <div v-if="scope.row.state">
              <el-button type="text" @click="isDisable(scope.row)"
                >禁用</el-button
              >
              <el-button type="text" disabled>修改</el-button>
              <el-button type="text" disabled>删除</el-button>
            </div>
            <div v-if="!scope.row.state">
              <el-button type="text" @click="isDisable(scope.row)"
                >启用</el-button
              >
              <el-button type="text" @click="editDirectory(scope.row)"
                >修改</el-button
              >
              <el-button type="text" @click="deleteDirectory(scope.row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-row>
        <el-col :span="8" :push="16">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.page - 0"
            :page-sizes="[5, 7, 10, 15]"
            :page-size="queryInfo.pagesize - 0"
            layout="prev, pager, next,sizes, jumper"
            :total="counts"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <!-- 新增目录对话框 -->
    <!-- 路由占位   -- addDirectoryDialog控制添加对话框显示隐藏-->
    <directorys-add
      v-if="addDirectoryDialog"
      :isedit="isEdit"
      @cancelDialog="closed"
      @confirmDialog="confirm"
      @closeDialog="closed"
      :row="row"
    ></directorys-add>
  </div>
</template>

<script>
// 获取列表 删除 改变状态 接口
import { list, changeState, remove } from '@/api/hmmm/directorys'
// 导入增加对话框组件
import DirectorysAdd from '@/module-hmmm/components/directorys-add'

export default {
  data () {
    return {
      // 图书列表信息，表格要渲染的数据
      bookList: [],
      // 数据列表的总数（total）
      counts: 0,
      // 查询目录列表参数
      queryInfo: {
        pagesize: 10
      },
      // 地址传过来参数（路由）
      urlInfo: false,
      // 学科名称
      directoryName: '',
      // 状态绑定数据（启用、禁用）
      state: '',
      // 状态数据（我拿过来用，数字转换成汉字，其实直接三元也OK）
      options: [
        { value: 1, label: '已启用' },
        { value: 0, label: '已禁用' }
      ],
      // 控制添加对话框显示隐藏
      addDirectoryDialog: false,
      // 判断当前是新增还是修改
      isEdit: false,
      // 发起修改存数据
      row: {},
      // 搜索节流阀-----节流---控制发送请求的频率
      searchSwitch: true
    }
  },
  // 组件模块
  components: {
    // 添加目录模块 子组件 弹出框
    DirectorysAdd
  },
  // watch监听器--监听路由变化
  watch: {
    // 监听路由变化
    $route: {
      handler: function (val, oldVal) {
        // 当路由变化重新给参数赋值
        this.urlInfo = this.$route.query.name
          ? { name: this.$route.query.name, id: this.$route.query.id }
          : false
        // 重新获取列表
        this.getDirectoryList()
      },
      deep: true
    }
  },
  // 这里data computed 及 路由数据都处理好了
  // 路由查询数据: this.$route.query.xx
  created () {
    // 获取url来的参数 有就保存
    this.urlInfo = this.$route.query.name
      ? { name: this.$route.query.name, id: this.$route.query.id }
      : false
    // 获取目录列表
    this.getDirectoryList()
  },
  methods: {
    // 调用接口获取目录列表
    async getDirectoryList () {
      const { data } = await list({
        ...this.queryInfo,
        subjectID: this.urlInfo.name ? this.urlInfo.id : null
      })
      // 将获取信息存下来
      this.bookList = data.items
      this.counts = data.counts
      this.queryInfo.page = data.page
      this.queryInfo.pagesize = data.pagesize
    },
    // 改变每页条数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      // 重新发起请求获取列表
      this.getDirectoryList()
    },
    // 点击改变页数
    handleCurrentChange (newPage) {
      this.queryInfo.page = newPage
      // 重新发起请求获取列表
      this.getDirectoryList()
    },
    // 点击根据当前信息查询
    searchBookLise () {
      // 判断节流阀
      if (this.searchSwitch) {
        // 当状态默认时 解决一直获取禁用 添加判断
        if (this.state === '') {
          this.state = null
        }
        // 将最新搜索值赋给查询条件：
        this.queryInfo.directoryName = this.directoryName // 右边是输入框的值，赋值给左边查询条件
        this.queryInfo.state = this.state
        // 优化页码------搜索将当前页数改为1
        this.queryInfo.page = 1
        // 刷新页面
        this.getDirectoryList()
        // 节流阀状态改为false
        this.searchSwitch = false
      }
    },
    // 点击顶部--清除按钮
    clearBtn () {
      // 清除当前搜索信息
      this.directoryName = ''
      this.state = ''
      // 清除储存信息
      this.queryInfo.directoryName = ''
      this.queryInfo.state = null
      // 获取页面信息
      this.getDirectoryList()
      // 重置节流阀
      this.searchSwitch = true
    },
    // 禁用与启用
    async isDisable (row) {
      if (row.state === 0) {
        // 当前状态为0  发起请求改变状态
        try {
          await changeState({ id: row.id, state: 1 })
          this.getDirectoryList()
          this.$message.success('操作成功')
        } catch (err) {
          this.$message.error('请求失败,请稍后再试')
        }
      } else {
        // 当前状态为1
        try {
          await changeState({ id: row.id, state: 0 })
          this.getDirectoryList()
          this.$message.success('操作成功')
        } catch (err) {
          this.$message.error('请求失败,请稍后再试')
        }
      }
    },
    // 点击删除当前目录
    async deleteDirectory (row) {
      // 发起请求删除
      // 询问是否删除
      const cancelButtonText = await this.$confirm(
        '此操作将永久删除该目录, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (cancelButtonText !== 'confirm') {
        // 取消删除
        return this.$message.info('取消了删除')
      }
      // 确认删除
      // 根据id 发起删除请求
      try {
        await remove(row)
        console.log()
        this.$message.success('已删除')
        //  刷新列表
        this.getDirectoryList()
      } catch (err) {
        this.$message.error('删除目录失败,请稍候再试')
        console.log(err)
      }
    },
    // 点击修改目录 ,渲染页面信息
    editDirectory (row) {
      // 将当前数据存起来
      this.row = row
      // 修改判断修改状态
      this.isEdit = true
      // 显示弹框
      this.addDirectoryDialog = true
    },
    // 确认添加或修改进行刷新页面和数据重置
    confirm () {
      this.getDirectoryList()
      // 重置信息
      this.row = {}
      this.isEdit = false
      this.addDirectoryDialog = false
    },
    // 弹框关闭或者用户取消父组件进行重置 操作
    closed () {
      this.row = {}
      this.isEdit = false
      this.addDirectoryDialog = false
    }
  }
}
</script>
<style scoped>
.oop{
  color: red;
  font-size: 20px;
  background-color: #fff;
}
.el-alert {
  margin-bottom: 15px;
}
.el-pagination{
  text-align: right;
}
</style>

<style scoped >
 .el-breadcrumb__inner {
  color: #000;
}
.el-input {
  width: 250px;
  margin-left: 5px;
}
.leftBtn {
  margin-left: 10px;
}
.hr {
  position: absolute;
  top: 40px;
  left: 0;
  width: 100%;
}
.searchRow {
  margin-top: 35px;
}
.strong {
  font-weight: 700;
}
.operate {
  margin-right: 6px;
}
.el-pagination {
  margin: 20px 0 10px;

}
.el-pagination /deep/.el-input--medium {
    width: 60px;
  }
.closeObject {
  margin-right: 5px;
  font-size: 14px;
  color: rgb(0, 119, 255);
}
.el-icon-back {
  margin-right: 5px;
}
.el-alert {
  margin-bottom: 10px;
  margin-top: 20px;
}
.addDirectory {
  margin-left: 130px;
}
.el-card{
  color: rgb(223, 20, 20);
}
</style>
